package com.chatai.config;

import com.chatai.service.ApiKeyService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Collections;

@Component
public class ApiKeyAuthFilter extends OncePerRequestFilter {
    
    @Autowired
    private ApiKeyService apiKeyService;
    
    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain)
            throws ServletException, IOException {
        
        // 从请求头获取API Key
        String apiKey = request.getHeader("X-API-Key");
        
        // 对于文件上传请求，只从请求头获取API key，不尝试获取请求参数
        // 因为在多部分请求解析前获取参数会导致MultipartException
        String contentType = request.getContentType();
        boolean isMultipartRequest = contentType != null && contentType.contains("multipart/form-data");
        
        // 如果不是多部分请求，且请求头中没有API key，才尝试从查询参数获取
        if (!isMultipartRequest && (apiKey == null || apiKey.isEmpty())) {
            apiKey = request.getParameter("api_key");
        }
        
        if (apiKey != null && !apiKey.isEmpty()) {
            // 验证API Key并获取用户
            apiKeyService.getUserByApiKey(apiKey).ifPresent(user -> {
                // 创建认证令牌
                UsernamePasswordAuthenticationToken authentication =
                        new UsernamePasswordAuthenticationToken(user, null, Collections.emptyList());
                
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            });
        }
        
        filterChain.doFilter(request, response);
    }
}